const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { Unauthorized } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

module.exports = async (req, res, next) => {
  try {
    console.log(req,'sssssss')
    const token = req.headers.token || req.query.token;
    console.log(token,'token')
    if (!token) {
      throw new Unauthorized('无权限访问');
    }
    const decoded = jwt.verify(token, process.env.SECRET);
    const { userId } = decoded;
    console.log(userId, 'userId');
    const user = await User.findByPk(userId);
    if (!user) {
      throw new Unauthorized('用户不存在');
    }
    if (user.role !== 100) {
      throw new Unauthorized('没有权限');
    }
    req.user = user;
    next();
  } catch (error) {
    failure(res, error);
  }
};
